package me.dqn.floatingtraffic.views;

import android.app.ActivityManager;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.dingmouren.colorpicker.ColorPickerDialog;
import com.dingmouren.colorpicker.OnColorPickerListener;

import java.util.List;

import me.dqn.floatingtraffic.R;
import me.dqn.floatingtraffic.bean.WindowSettings;
import me.dqn.floatingtraffic.service.BackService;

import static android.content.ContentValues.TAG;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        setUpViews();
    }

    private void setUpViews() {
        Button startButton = findViewById(R.id.id_startBtn);
        /**
         * start background service if it isn't running now.
         */
        startButton.setOnClickListener(view -> {
            boolean isServiceRunning = isBackServiceRunning(MainActivity.this.getApplicationContext(), getString(R.string.BACK_SERVICE_NAME));
            if (!isServiceRunning) {
                if (hasPermissionToReadNetworkStats()) {
                    if (Build.VERSION.SDK_INT >= 23) {
                        if (!Settings.canDrawOverlays(getApplicationContext())) {
                            //启动Activity让用户授权
                            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
                            startActivity(intent);
                            return;
                        } else {
                            startBackService();
                        }
                    } else {
                        startBackService();
                    }
                } else {
                    Toast.makeText(MainActivity.this, "需要读取系统信息的权限", Toast.LENGTH_SHORT).show();
                }
            }
        });

        Button colorPicker = findViewById(R.id.colorPicker);
        colorPicker.setBackgroundColor(WindowSettings.speedColor);
        colorPicker.setOnClickListener(view -> {
            int preColor = WindowSettings.speedColor;
            ColorPickerDialog colorPickerDialog = new ColorPickerDialog(
                    MainActivity.this,
                    WindowSettings.speedColor,
                    new OnColorPickerListener() {
                        @Override
                        public void onColorCancel(ColorPickerDialog dialog) {
                            WindowSettings.speedColor = preColor;
                            colorPicker.setBackgroundColor(preColor);
                        }

                        @Override
                        public void onColorChange(ColorPickerDialog dialog, int color) {
                            WindowSettings.speedColor = color;
                            colorPicker.setBackgroundColor(color);
                        }

                        @Override
                        public void onColorConfirm(ColorPickerDialog dialog, int color) {
                            WindowSettings.speedColor = color;
                            colorPicker.setBackgroundColor(color);
                        }
                    }
            ).show();
        });

        EditText fontSizeInput = findViewById(R.id.fontSize);
        fontSizeInput.setText(WindowSettings.windowFontSize + "");

        Button updateSize = findViewById(R.id.updateSize);
        updateSize.setOnClickListener(v -> {
            String value = fontSizeInput.getText().toString();
            int pre = WindowSettings.windowFontSize;
            if (value!=null && !value.trim().equals("")){
                WindowSettings.windowFontSize = Integer.valueOf(value.trim());
            }else {
                WindowSettings.windowFontSize = pre;
            }
        });
    }

    /**
     * start background service
     */
    private void startBackService() {
        Toast.makeText(MainActivity.this, "Create Service", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent();
        intent.setClass(MainActivity.this, BackService.class);
        startService(intent);
    }

    /**
     * check background service is running or not
     *
     * @param context
     * @param serviceName
     * @return
     */
    private boolean isBackServiceRunning(Context context, String serviceName) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> runningServiceInfos = activityManager.getRunningServices(30);
        runningServiceInfos.stream()
                .forEach(runningServiceInfo -> Log.i(TAG, "isBackServiceRunning: " + runningServiceInfo.service.getClassName()));
        long count = runningServiceInfos.stream()
                .filter(runningServiceInfo -> runningServiceInfo.service.getClassName().equals(serviceName))
                .count();
        return count > 0 ? true : false;
    }

    /**
     * check if have permission to get traffic data
     *
     * @return
     */
    private boolean hasPermissionToReadNetworkStats() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        final AppOpsManager appOps = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
        int mode = appOps.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS,
                android.os.Process.myUid(), getPackageName());
        if (mode == AppOpsManager.MODE_ALLOWED) {
            return true;
        }
        Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
        startActivity(intent);
        return false;
    }


}
